package cn.ycq.im.commons.utils;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;

public class FreemarkerRenderUtils {

    private static final Configuration DEFAULT;
    static {
        DEFAULT = new Configuration();
        ClassTemplateLoader templateLoader = new ClassTemplateLoader(FreemarkerRenderUtils.class, "/temp");
        DEFAULT.setTemplateLoader(templateLoader);
        DEFAULT.setEncoding(Locale.getDefault(),"UTF-8");
    }


    public static Configuration getDefaultConfiguration(){
        return DEFAULT;
    }

    public static void process(String templateName, Map<String,Object> props, Writer writer) throws IOException, TemplateException {
        if(props == null){
            props = Collections.emptyMap();
        }
        Template template = DEFAULT.getTemplate(templateName);
        template.process(props,writer);
    }
    public static String render(String templateName,Map<String,Object> props) throws IOException, TemplateException {
        StringWriter stringWriter = new StringWriter();

        process(templateName,props,stringWriter);

        return stringWriter.toString();
    }

}
